<template>
  <div class="flex m-t-16">
    <el-avatar :src="curUser.avatar" class="shrink-0 m-l-10" />
    <div class="flex-1 m-l-16">
      <div v-show="false" ref="plainBox" v-html="content"></div>
      <tinymce-editor ref="editor" v-model="content" />
      <el-button type="primary" @click="doComment" :loading="loading" class="m-t-10">
        发布跟贴
      </el-button>
      <span class="m-l-5 el-alert--error is-light">{{ error }}</span>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { formatComment } from '../format';

export default {
  name: 'comments-container', // 一级评论（富文本）
  data() {
    return {
      content: '',
      loading: false,
      error: '',
    };
  },
  computed: {
    ...mapState({
      curDoc: 'currentDocument',
      curUser: 'currentUser',
    }),
    doCommentParams() {
      return {
        placement: 'ProductFile',
        placementId: this.curDoc.id,
        receiveUserId: this.curDoc.author.id,
        content: this.content,
      };
    },
  },
  methods: {
    doComment() {
      const plainText = this.$refs.plainBox.innerText;
      if (plainText.trim() === '') {
        this.error = '跟帖内容不能为空';
        return;
      }
      this.loading = true;
      this.$api.comments.create(this.doCommentParams)
        .then((res) => {
          this.$message.success('发送成功');
          this.$refs.editor.setContent('');
          this.$emit('commented', formatComment(res.data));
        })
        .catch(() => {})
        .then(() => { this.loading = false; });
    },
  },
  watch: {
    error() { setTimeout(() => { this.error = ''; }, 2000); },
  },
};
</script>

<style></style>
